<?php declare(strict_types=1);


namespace PinWuYun\domain\data\YouZanData;

use Exception;
use PinWuYun\domain\helper\GoodsPriceHelper;
use PinWuYun\domain\helper\PropHelper;
use PinWuYun\domain\service\youZanServer\ImageServer;
use PinWuYun\domain\service\youZanServer\TokenServer;

/**
 * Created: by zhiJie
 * Date: 2021/6/22
 */
class GoodsData
{
    /**
     * 添加商品，参数填充
     * @param array $spuDetail
     * @param string $accessToken
     * @return array
     * @throws Exception
     */
    public function buildAddItem(array $spuDetail, string $accessToken): array
    {
        $skuList = [];
        $skuValueProps = [];
        $propHelper = new PropHelper();
        $priceHelper = new GoodsPriceHelper();
        foreach ($spuDetail['skuList'] as $index => $sku) {
            // 有赞的单位是分,星链是元 这里 * 10
            $skuChannelPrice = (float)$sku['salePrice']['channelPrice'] * 10;
            $skuRetailPrice = (float)$sku['salePrice']['retailPrice'] * 10;
            $priceHelper->checkMaxPrice($skuChannelPrice, $skuRetailPrice);
            $priceHelper->checkMinPrice($skuChannelPrice, $skuRetailPrice);

            $skuList[$index] = [
                'weight' => 1,
                 //'sku_props' => $skuProps,
                'price' => (int)$skuRetailPrice,
                'max_guide_price' => (int)$priceHelper->getMaxPrice(),
                'min_guide_price' => (int)$priceHelper->getMinPrice(),
                'cost_price' => (int)$skuChannelPrice,
                'sku_no' => $sku['code'],
                'stock_num' => $sku['inventory']['inventoryCount'],
            ];
            // 加上sku属性
            $skuProps = [];
            foreach ($sku['skuPropertyList'] as $property) {
                $skuProps[] = [
                    'prop_name' => $property['name'],
                    'prop_name_id' => $propHelper->getIdInNameGroup($property['name']),
                    'prop_value_name' => $property['val'],
                    'prop_value_id' => $propHelper->getIdInValueGroup($property['val']),
                ];
            }
            $skuList[$index]['sku_props'] = $skuProps;
            // 上传logo图
            $response = ImageServer::uploadImageOne($accessToken, $sku['goodsLogo']);
            $skuValueProps[] = [
                'name' => $skuProps[0]['prop_value_name'],
                'img_id' => $response['data']['image_id'],
                'id' => $skuProps[0]['prop_value_id']
            ];
        }

        // 获取商品主图，上传到星链，获取商品图id
        $imagesId = $this->uploadPicture($spuDetail['detailImgUrlList'], $accessToken); // , 3328841382, 3328841557

        return [
                'item_type' => 0,
                // 商品自定义编码 这里用来存星链spuId
                'item_no' => $spuDetail['spuId'],
                // sku图片, 去除空的，有的上传失败会返回空
                'image_ids' => array_filter($imagesId),
                'desc' => $spuDetail['detailInfo'],
                'item_price_param' => [
                    'origin' => (string)$priceHelper->getMinPrice(),
                    'cost_price'=>  (int)$priceHelper->getMinPrice(),
                    // 'min_guide_price' => (int)$priceHelper->getMinPrice(),
                    'price' =>  (int)$priceHelper->getMinPrice(),
                    // 'max_guide_price' => (int)$priceHelper->getMaxPrice(),
                ],
                // 配送属性集
                'item_delivery_param' => [
                    "delivery_setting" => [
                        "express" => true
                    ],
                    "postage" => 000
                ],
                'title' => $spuDetail['name'],
                'sku_list' => $skuList,
                'sku_value_props' => $skuValueProps,
                // 微信分享描述
                "summary" => $spuDetail['name'],
                "sell_point" => $spuDetail['name'],
                "hide_stock" => 1,
                "is_display" => 1,
                "join_level_discount" => 1,
                "quantity" => 1000,
                "prepare_time" => 500,
                "item_weight" => 2003,
                "total_stock" => 1000,
                'extra_param' => [
                    'holidays_available' => true
                ],
                // 售后信息
                /*'post_sale_param' => [
                    'refund_param' => [
                        'support_refund' => false,
                    ]
                ],*/
                // youzan.item.template.list.search】接口获得商品页模板ID
                // 'template_id' => '',
            ];
    }

    /**
     * 更新商品时主要数据处理
     * @throws Exception
     */
    public function buildUpdateItem(array &$spuDetail, $itemId): array
    {
        $accessToken = TokenServer::getAccessToken();
        $skuJson = [];
        $skuValueProps = [];
        // 商品总数
        $total = 0;
        $propHelper = new PropHelper();
        foreach ($spuDetail['skuList'] as $sku) {
            // 加上sku属性
            $skuProps = [];
            foreach ($sku['skuPropertyList'] as $property) {
                $skuProps[] = [
                    'k' => $property['name'],
                    'kid' => $propHelper->getIdInNameGroup($property['name']),
                    'v' => $property['val'],
                    'vid' => $propHelper->getIdInValueGroup($property['val']),
                ];
            }
            // 每个sku的数量加起来
            $total += $sku['inventory']['inventoryCount'];
            $skuJson[] = [
                "price" => $sku['salePrice']['channelPrice'] * 10,
                "quantity" => $sku['inventory']['inventoryCount'],
                "item_no" => $sku['code'],
                "skus" => $skuProps,
            ];
            // 上传logo图
            $response = ImageServer::uploadImageOne($accessToken, $sku['goodsLogo']);
            $skuValueProps[] = [
                'v' => $skuProps[0]['v'],
                'img_url' => $response['data']['image_url'],
            ];
        }

        // 获取商品主图，上传到星链，获取商品图id
        $imagesId = $this->uploadPicture($spuDetail['detailImgUrlList']);
        return [
            'item_id' => $itemId,
            'express' => true,
            //有赞用户id，用户在有赞的唯一id。推荐使用。微商城连锁店铺yz_open_id必传。
//            'yz_open_id' => ,
            'sku_stocks' => json_encode($skuJson),
            'quantity' => $total,
            'sku_images' => json_encode($skuValueProps),
            'desc' => $spuDetail['detailInfo'],
            'title' => $spuDetail['name'],
            'item_no' => $spuDetail['spuId'],
            // 'template_id' => ,
            'sell_point' => $spuDetail['name'],
            'image_ids' => array_unique($imagesId),
        ];
    }

    /**
     * 更新商品时sku数据处理
     */
    public function buildUpdateSkuItem(array &$spuDetail): array
    {
        // TODO
        return [
            'sku_id' => '',
            'item_id' => '',
            'quantity' => '',
            'item_no' => $spuDetail['spuId'],
        ];
    }

    /**
     * 上传所有图片到有赞，获取图片id数组
     * @throws Exception
     */
    public function uploadPicture(array &$pictures, string $accessToken = null): array
    {
        $imagesId = [];
        $accessToken = $accessToken ?: TokenServer::getAccessToken();
        foreach ($pictures as $picture) {
            $response = ImageServer::uploadImageOne($accessToken, $picture);
            $imagesId[] = $response['data']['image_id'];
        }
        return $imagesId;
    }


}